<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;

class Base extends Controller
{
    public $page_info = [];
    public $exception = [];
    public $login_user = null;

    public function __construct(){
        parent::__construct();

        $login_user = session("cch_admin");
        $action = strtolower(request()->action());
        if(empty($login_user) && !in_array($action, $this->exception)){
            $this->redirect(url('admin/login'));
        }

        $this->login_user = $login_user;
        $this->page_info = [
            'action'=>$action,
            'controller'=>strtolower(request()->controller()),
            'path'=>request()->path()
        ];
        $this->page_info['controller'] = explode('/', $this->page_info['path'])[1];
        $this->assign([
            'login_user'=>$login_user,
            'Db'=>Db,
        ]);

        // 记录操作日志
        if (!empty($login_user)) {
            Db::name('logs')->insert([
                'controller'=>request()->controller(),
                'action'=>request()->action(),
                'admin_id'=>$login_user['id'],
                'params'=>json_encode($_REQUEST,JSON_UNESCAPED_UNICODE),
                'ctime'=>date('Y-m-d H:i:s')
            ]);
        }
    }

    /**
     * 上传图片
     * @Author   CCH
     * @DateTime 2020-08-15T17:26:24+0800
     * @return   [type]                   [description]
     */
    public function upload(){
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');
        // 移动到框架应用根目录/public/uploads/ 目录下
        if($file){
            $filename = $file->getInfo()['name'];
            $ext = explode(".", $filename);//拆分获取图片名
            $ext = $ext[count($ext) - 1];//取图片的后缀名
            $ext = strtolower($ext);
            $types = ["jpg", "gif", 'png', 'bmp','jpeg','pdf','doc','docx','xls','xlsx','txt'];
            if (!in_array($ext, $types)) {
                return json(['code'=>5000,'msg'=>'文件格式不支持，请上传标准图片文件']);
            }
            
            $info = $file->move('./uploads');
            if($info){
                $result = [
                    'extension'=>$info->getExtension(),
                    'savename'=>str_replace('\\', '/', $info->getSaveName()),
                    'filename'=>$info->getFilename()
                ];
                return json(['code'=>2000,'msg'=>'上传成功','data'=>$result]);
            }else{
                return json(['code'=>5000,'msg'=>$file->getError()],500);
            }
        }
    }

    public function index($map=[]){
    	$model = $this->model;
    	$page_param = [
    		'page'=>input('page',1),
    		'list_rows'=>input('page_size',20)
    	];
    	$list = $model->where($map)->order('id','desc')->paginate($page_param);
        $page = $list->render();
    	return view('index', [
            'list'=>$list->toarray(),
            'page'=>$page
        ]);
    }

    public function view($id){
        $model = $this->model;
        $data = $model->where('id',$id)->find();
        return view('view', [
            'data'=>$data
        ]);
    }

    public function saveData($save_data){
        $model = $this->model;
        if (request()->isPost()) {
            $t_fields = $model->getTableFields();
            if (!isset($save_data['ctime']) && in_array('ctime', $t_fields)) {
                $save_data['ctime'] = time();
            }
            if (!isset($save_data['utime']) && in_array('utime', $t_fields)) {
                $save_data['utime'] = time();
            }
            if ( $model->save($save_data) ) {
                $this->success("添加成功",url('index'));
            }else{
                $this->error("添加失败");
            }
        }
        return view(emptyDef($this->page_info['view'],'common/save'), [
            
        ]);
    }

    public function updateData($id,$save_data){
        $model = $this->model;
        if (request()->isPost()) {
            $t_fields = $model->getTableFields();
            if (!isset($save_data['utime']) && in_array('utime', $t_fields)) {
                $save_data['utime'] = time();
            }
            if ( $model->where('id',$id)->update($save_data) !== false ) {
                $this->success("编辑成功",url('index'));
            }else{
                $this->error("编辑失败");
            }
        }
        $data = $model->where('id',$id)->find();
        return view(emptyDef($this->page_info['view'],'common/save'), [
            'data'=>$data
        ]);
    }

    public function delete($id){
        $model = $this->model;
        if ( $model->where('id',$id)->delete() ) {
            $this->success("删除成功");
        }else{
            $this->error("删除失败");
        }
    }

    public function moreDelete($ids){
        $model = $this->model;
        if ( $model->where('id','in',$ids)->delete() ) {
            $this->success("删除成功");
        }else{
            $this->error("删除失败");
        }
    }

    public function changeData($id,$save_data){
        $model = $this->model;
        if ( $model->where('id',$id)->update($save_data) !== false ) {
            $this->success("操作成功");
        }else{
            $this->error("操作失败");
        }
    }

    public function getVal($id,$field){
        $model = $this->model;
        return $model->where('id',$id)->value($field);
    }


}
